<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\BlackCard\Controllers;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\BlackCard\BlackBanner;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Doraemon\tools\ImgUrl;
use Biz\model\brandIndex\BrandBanner;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;


class BannerController extends Controller
{
    const PAGE_SIZE = 20;
    const DEFAULT_HAOHAOZHU_UID = 11941;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function bannerList(Request $request, Content $content)
    {
        $brand_list = (array) BlackBanner::getBanners();
        $count = (int) count($brand_list);

        $gridModel = new pGridDataModel($brand_list, $count, []);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();

            $grid->column('id', 'banner_id')->sort();
            $grid->column('banner_comment', 'banner备注名');
            $grid->column('pic_id', 'banner图片')->display(function() {
                return "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->pic_id, ImgUrl::IMAGE_SIZE_OP_ORI)."' width=300 /><br>添加时间：".$this->addtime."<br>最后修改时间：".$this->edittime;
            })->width(350);
            $grid->column('start_time', '展示时间')->display(function() {
                return "开始展示时间：".$this->start_time."<br>展示结束时间：".$this->end_time;
            })->width(250);
            $grid->column('end_time', '展示状态')->display(function() {
                $curr_time = date('Y-m-d H:i:s', time());
                if($this->start_time<$curr_time && $this->end_time>$curr_time) {
                    return '<span style="color:yellowgreen">展示中</span>';
                } else if ($this->end_time<$curr_time) {
                    return '<span style="color:red">已下架</span>';
                } else {
                    return '<span style="color:deeppink">未开始</span>';
                }
            });
            $grid->column('link', '跳转链接')->display(function() {
                if($this->link) {
                    return "<a href='".$this->link."' target='_blank'>点击跳转</a>";
                } else {
                    return '-';
                }

            })->width(150);
        });

        return $content
            ->header('banner管理')
            ->body($listGrid);

    }

    //添加banner
    public function addBanner(Request $request, Content $content)
    {
        $request = $request->all();
        return $content
            ->header('添加banner')
            ->breadcrumb(
                ['text' => 'banner管理', 'url' => '/blackCard/banner/index'],
                ['text' => '添加banner', 'url' => '/blackCard/banner/index/create']
            )
            ->body(self::editAction($request, $id = 0));

    }

    //修改banner
    public function editBanner(Request $request, Content $content, $id)
    {

        $request = $request->all();
        return $content
            ->header('banner管理')
            ->breadcrumb(
                ['text' => 'banner列表', 'url' => '/blackCard/banner/index'],
                ['text' => '修改banner', 'url' => '/blackCard/banner/index/'.$id.'/edit']
            )
            ->body(self::editAction($request, $id));
    }

    public function editAction($request, $id = 0)
    {
        $data = [];
        if($id != 0) {
            //修改
            $data = BlackBanner::getBannerById($id);
            $data['link'] = [
                'link_type' => $data['link_type'],
                'link_params' => $data['link_params'],
            ];
            $form = new Form($data);
            $form->hidden('id');
        } else {
            //添加
            $data['start_time'] = date('Y-m-d H:i:s', time());
            $data['end_time'] = date('Y-m-d H:i:s', time()+86400*7);
            $form = new Form($data);
        }
        $form->text('banner_comment', 'banner备注名')->setWidth(4, 2)->required('不能为空')->help('仅用于后台备注，不展示');
        $form->imgUpload('pic_id', 'banner图', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->number('banner_sort')->help('banner排序，会按照由小到大的顺序在前端展示')->default(0);
        $form->linkSelect('link', '跳转链接');
        $form->datetimeRange('start_time', 'end_time', '展示时间');
        $form->action('/admin/blackCard/banner/index/save');

        return $form->render();
    }

    //提交
    public function save(Request $request, Content $content)
    {
        $request = $request->all();
        $rs = false;
        $data['banner_comment'] = $request['banner_comment'];
        $data['pic_id'] = $request['pic_id'];
        $data['banner_sort'] = (int) $request['banner_sort'];
        $data['start_time'] = $request['start_time'];
        $data['end_time'] = $request['end_time'];
        $data['link_type'] = $request['link_type'];
        $data['link_params'] = json_encode($request['link_params'], JSON_UNESCAPED_UNICODE);
        $data['link'] = LinkFormat::generateSingleLink($request['link_type'], $request['link_params']);
        $data['banner_status'] = BrandBanner::STATUS_NORMAL;
        $data['admin_id'] = Admin::user()->id;

        if(isset($request['id']) && $request['id']) {
            $data['edittime'] = date('Y-m-d H:i:s', time());
            //修改
            $rs = BlackBanner::editData($data, ['id' => $request['id']]);
        } else {
            //添加
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = BlackBanner::addData($data);
        }

        if($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/blackCard/banner/index')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'. BrandBanner::error()
            ]);
            return redirect('/admin/blackCard/banner/index')->with(compact('error'));
        }
    }

    //删除banner
    public function delBanner($id)
    {
        $data = BlackBanner::getBannerById($id);
        if($data) {
            $data['banner_status'] = BlackBanner::STATUS_DELETE;
            $data['edittime'] = date('Y-m-d H:i:s', time());

            $rs = BlackBanner::editData($data, ['id' => $id]);
            if($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    //拖动排序
    public function sort(Request $request)
    {
        $request = $request->all();
        $sorts = $request['sort'];
        if($sorts && is_array($sorts)) {
            foreach($sorts as $id=> $sort) {
                $data['banner_sort'] = $sort;
                $data['edittime'] = date('Y-m-d H:i:s', time());
                BlackBanner::editData($data, ['id' => $id]);
            }
        }
    }

}
